#ifndef TF_MODBUS_H
#define TF_MODBUS_H

#include <QDebug>
#include <QtSerialPort/qserialport.h>
#include <qeventloop.h>

#include <qsocketnotifier.h> //imx6

#define MB_FUNC_WR_MULTI       0x10
#define MB_FUNC_WR_SINGLE      0x06
#define MB_FUNC_RD_HOLDING     0x03
#define MB_FUNC_WR_MULTI_REGS  0x10


typedef struct
{
#pragma pack(2)
    union
    {
        uint8_t buffer[4];
        struct
        {
            float    reg_flo;
            uint16_t reg_u16;
        } data;
    };

#pragma pack(2)

} DATA_TYPE_t;


class tf_modbus
{
  //  Q_OBJECT

public:
    tf_modbus();
    ~tf_modbus();

    int tf_modbus_open();
    void tf_modbus_close();

    void serialWirte(unsigned char *buf,int buf_Len);
    void mb_delay(int mSec);

        /*
            uiButtonConnectStus: 0 conncet   1: disconncet
            comPort: com name, such as COM1
        */
    bool tf_modbusDeviceHandle(bool isUiButtonConnect); //true: opened   false: open failure

    int     sendReadHoldingReg(uint16_t *readVal,quint16 serverAddr);
    int     sendReadMultiHoldingReg(uint16_t *readBuf, quint16 serverAddr, quint16 reg_num);
    int     sendReadFloatReg(float *readVal, quint16 serverAddr);
    int     sendReadMultiFloatReg(float *readBuf, quint16 serverAddr, quint16 reg_num); //success：return 0    failure：return -1 ..
    void    sendWriteHoldingReg(quint16 serverAddr, quint16 value);
    void    sendWriteMultiHoldingReg(uint16_t *writeBuf, quint16 serverAddr, quint16 reg_quantity);
    void    sendWriteFloatReg(quint16 serverAddr, float value);
    void    sendReadRequest(QVector<quint16> &buf,quint16 startAddr, qint16 registerNum);
    void    sendWriteRequest();

    uint8_t slaveID;
    QByteArray recvArr;
    int fd;

private slots:
    void remoteDataIncoming();

protected:





private:

    bool uiButtonConnectStus = false; //false: Not connect   true:connect

    static const quint16 modbus_crc16_table[256];
    quint16  mb_crc16(unsigned char *crcBuf, int nSize);




};

#endif // TF_MODBUS_H
